<template>
  <basic-container>
    <el-row style="margin-bottom: 20px">
      <el-form :model="form">
        <el-col :span="4">
          <el-form-item label-width="0">
            <b class="mainTitle">大学内部审计总览</b>
          </el-form-item>
        </el-col>
        <el-col :span="15">
        </el-col>
        <el-col :span="5">
<!--          <el-form-item label="年度">
            <el-select v-model="query.planHeadYear" clearable @change="handleYearChange">
              <el-option v-for="planHeadYear in planHeadYears"
                         :key="planHeadYear"
                         :label="planHeadYear"
                         :value="planHeadYear">
              </el-option>
            </el-select>
          </el-form-item>-->
        </el-col>
      </el-form>
    </el-row>
    <el-row :gutter="24">
      <el-col :span="7">
        <div class="partition">
          <div class="partition" style="height: 173px; position: relative;">
            <b class="subtitle">整改完成情况</b>
            <div ref="RCSChart" style="position: absolute; top: 0; left: 0; width: 100%; height: 173px;"></div>
          </div>
          <div class="partition" style="height: 173px; position: relative;">
            <b class="subtitle">本年度工程审计金额</b>
            <div ref="AEAAChart" style="position: absolute; top: 0; left: 0; width: 100%; height: 173px;"></div>
          </div>
          <div class="partition">
            <b class="subtitle">本年度审计项目进展</b>
            <el-table v-loading="loading" :data="form.projectData" border
                      header-row-class-name="container-table-header"
                      :header-cell-style="{textAlign: 'center'}"
                      stripe highlight-current-row height="184"
                      ref="projectData"
                      class="custom-table">
              <el-table-column label="序号" prop="index"  width="50">
              </el-table-column>
              <el-table-column label="项目名称" prop="projectName">
              </el-table-column>
              <el-table-column label="项目进度" prop="projectProgress" width="80">
                <template slot-scope="scope">
                  <DictTag :options="dict.type.project_progress" :value="scope.row.projectProgress"></DictTag>
                </template>
              </el-table-column>
              <el-table-column label="立项时间" prop="projectDate" width="85">
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
      <el-col :span="10">
        <div class="partition">
          <el-tabs v-model="activeName" @tab-click="handleClick" type="card" :stretch="true">
            <el-tab-pane name="常规审计成果总览">
              <template #label>
                <b style="text-align: center">常规审计成果总览</b>
              </template>
            </el-tab-pane>
            <el-tab-pane name="工程审计成果总览">
              <template #label>
                <b style="text-align: center">工程审计成果总览</b>
              </template>
            </el-tab-pane>
          </el-tabs>
          <div ref="radarChart" style="width: 100%; height: 400px;"></div>
          <div style="width: 100%; height: 155px;
          background: linear-gradient(to top,#74c0ea 0%, #b7ddf2 20%, #dff0f9 50%, #FFFFFF 100%);">
            <el-row :gutter="20">
              <el-col :span="2">
              </el-col>
              <el-col :span="10">
                <div>
                  <el-result subTitle="本年度审计项目数">
                    <template #title>
                      <b class="statisticNumber">{{ animatedValues.projectCount.toFixed(0) }}</b> 个
                    </template>
                  </el-result>
                </div>
              </el-col>
              <el-col :span="10">
                <div>
                  <el-result subTitle="本年度发现问题数">
                    <template #title>
                      <b class="statisticNumber">{{ animatedValues.problemCount.toFixed(0) }}</b> 个
                    </template>
                  </el-result>
                </div>
              </el-col>
              <el-col :span="2">
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="2">
              </el-col>
              <el-col :span="10">
                <div>
                  <el-result subTitle="本年度审计问题发现金额">
                    <template #title>
                      <b class="statisticNumber">{{ animatedValues.discoverAmount.toFixed(2) }}</b> 元
                    </template>
                  </el-result>
                </div>
              </el-col>
              <el-col :span="10">
                <div>
                  <el-result subTitle="本年度审计金额">
                    <template #title>
                      <b class="statisticNumber">{{ animatedValues.engineeringAmount.toFixed(2) }}</b> 元
                    </template>
                  </el-result>
                </div>
              </el-col>
              <el-col :span="2">
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="partition" style="height: 173px; position: relative;">
          <b class="subtitle">年度发现问题分布</b>
          <div ref="hillChart" style="position: absolute; top: 0; left: 0; width: 100%; height: 173px;"></div>
        </div>
        <div class="partition" style="height: 173px; position: relative;">
          <b class="subtitle">审计知识库建设情况</b>
          <div ref="knowledgeChart" style="position: absolute; top: 0; left: 0; width: 100%; height: 200px;"></div>
        </div>
        <div class="partition">
          <b class="subtitle">审计公示</b>
          <el-table v-loading="loading" :data="form.procurementData" border
                    header-row-class-name="container-table-header"
                    :header-cell-style="{textAlign: 'center'}"
                    stripe highlight-current-row height="184"
                    ref="procurementData"
                    class="custom-table">
            <el-table-column label="序号" prop="index"  width="50">
            </el-table-column>
            <el-table-column label="项目名称" prop="projectName">
            </el-table-column>
            <el-table-column label="文号" prop="documentNumber" width="150">
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </basic-container>
</template>

<script>
import "@/styles/flightDeck.scss";
import * as echarts from 'echarts';
import {listPlanHeadYear} from "@/api/adis/work/plan";
import Template from "@/views/adis/base/template";
export default {
  name: "flightDeck",
  components: {Template},
  dictTypes: ['project_progress'],
  data() {
    return {
      scrollTimer: '', // 自动滚动的定时任务
      activeName: '常规审计成果总览',
      loading: false,
      /*数字滚动效果 start */
      animatedValues: {
        projectCount: 0,
        problemCount: 0,
        discoverAmount: 0,
        engineeringAmount: 0
      },
      animationDuration: 1200, // 动画时长，单位毫秒
      animationStep: 10, // 每步动画的时间间隔，单位毫秒
      /*数字滚动效果 end */
      form: {
        engineeringStatistic: {
          projectCount: 17,
          problemCount: 16,
          discoverAmount: 10365.25,
          engineeringAmount: 548205.37,
        },
        generalStatistic: {
          projectCount: 24,
          problemCount: 35,
          discoverAmount: 17450.47,
          engineeringAmount: 872834.81,
        },
        RCSChartData: [ // 整改完成情况图表数据
          { value: 5,  itemStyle: { color: '#d85757' }, name: '未整改' , },
          { value: 12, itemStyle: { color: '#536fcb' }, name: '正在整改' ,},
          { value: 9,  itemStyle: { color: '#5fd375' }, name: '已整改' , },
          { value: 4,  itemStyle: { color: '#ffbe4f' }, name: '无法整改' , },
        ],
        AEAAChartData: [ // 本年度工程审计金额
          { value: 154820.46, itemStyle: { color: '#009E73' }, name: '送审金额' ,},
          { value: 16490.00,  itemStyle: { color: '#2196F3' }, name: '审减金额' ,},
        ],
        radarChart: {// 成果总览
          engineeringData: [{ value: [17, 5, 7, 11, 24, 28, 12, 16], }],
          generalData: [{ value: [9, 21, 15, 6, 8, 18, 11, 24], }],
        },
        hillChartData: [ // 发现问题分布
          {value: 14, itemStyle: {color: '#19e9e9'}},
          {value: 17, itemStyle: {color: '#edb545'}},
          {value: 8, itemStyle: {color: '#3784ea'}},
          {value: 12, itemStyle: {color: '#55c380'}},
          {value: 9, itemStyle: {color: '#78a1df'}},
          {value: 6, itemStyle: {color: '#e6616f'}},
          {value: 8, itemStyle: {color: '#e9e16b'}},
        ],
        knowledgeChartData: [23, 41, 12, 34, 9], // 知识库建设
        projectData: [
          {
            index: 1,
            projectName: "先进材料性能研究",
            projectProgress: 5,
            projectDate: "2023-01-10",
          },
          {
            index: 2,
            projectName: "人工智能在医疗诊断中的应用",
            projectProgress: 6,
            projectDate: "2023-02-10",
          },
          {
            index: 3,
            projectName: "可持续能源技术研究",
            projectProgress: 5,
            projectDate: "2023-03-15",
          },
          {
            index: 4,
            projectName: "气候变化对农业产量的影响研究",
            projectProgress: 4,
            projectDate: "2023-04-20",
          },
          {
            index: 5,
            projectName: "网络安全防御机制优化研究",
            projectProgress: 7,
            projectDate: "2023-05-05",
          },
          {
            index: 6,
            projectName: "新型药物开发及其临床试验研究",
            projectProgress: 6,
            projectDate: "2023-06-10",
          },
          {
            index: 7,
            projectName: "大数据分析在市场营销策略中的应用",
            projectProgress: 4,
            projectDate: "2023-07-15",
          },
          {
            index: 8,
            projectName: "虚拟现实技术在教育领域的应用研究",
            projectProgress: 5,
            projectDate: "2023-08-20",
          },
        ],
        procurementData: [
          {
            index: 1,
            projectName: "2023年度部门预算执行情况审计",
            documentNumber: "浙工大审通（2023）1号",
          },
          {
            index: 2,
            projectName: "2023年度科研经费使用审计",
            documentNumber: "浙工大审通（2023）2号",
          },
          {
            index: 3,
            projectName: "2023年第一季度财务报表审计",
            documentNumber: "浙工大审通（2023）3号",
          },
          {
            index: 4,
            projectName: "2023年度基建项目结算审计",
            documentNumber: "浙工大审通（2023）4号",
          },
          {
            index: 5,
            projectName: "2023年半年度财务收支审计",
            documentNumber: "浙工大审通（2023）5号",
          },
          {
            index: 6,
            projectName: "2023年度专项经费绩效审计",
            documentNumber: "浙工大审通（2023）6号",
          },
          {
            index: 7,
            projectName: "2023年第三季度财务合规性审计",
            documentNumber: "浙工大审通（2023）7号",
          },
          {
            index: 8,
            projectName: "2023年度年终财务决算审计",
            documentNumber: "浙工大审通（2023）8号",
          }
        ],
      },
      query: {
        planHeadYear: '',
      },
      planHeadYears: [],
    };
  },
  created() {
    this.onLoad();
  },
  computed: {

    // 指定图表的配置项和数据
    RCSChartOption() {// 整改完成情况图表数据
      return {
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return params.name + ': ' + params.value;
          },
        },
        legend: {
          top: '35%',
          width: '130px',
          left: '5',
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '80%'],
            center: ['65%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 5,
              borderColor: '#fff',
              borderWidth: 1
            },
            label: {
              show: true,
              position: 'outer',
              formatter: '{c}',
            },
            // 在这里使用 this.form.RCSChartData
            data: this.form.RCSChartData,
          }
        ],
      }
    },
    AEAAChartOption() { // 本年度工程审计金额
      // 从 Vue 组件的 data 或 props 中获取数据
      const chartData = this.form.AEAAChartData;

      // 定义一个查找函数，用于在 legend.formatter 中根据名称查找值
      const findValueByName = (name) => {
        let value = null;
        chartData.forEach(item => {
          if (item.name === name) {
            value = item.value;
          }
        });
        return value;
      };
      return {
        tooltip: {
          trigger: 'item',
            formatter: function(params) {
            return params.name + ': ￥' + params.value.toFixed(2);
          },
        },
        legend: {
          top: '35%',
          width: '130px',
          left: '5',
          formatter: function(name) {
            const value = findValueByName(name);
            return value !== null ? name + ': \n\n￥' + value.toFixed(2) : name;
          },
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '80%'],
            center: ['65%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 5,
              borderColor: '#fff',
              borderWidth: 1
            },
            label: {
              show: false,
            },
            data: chartData,
          }
        ],
      }
    },
    radarChartOption() {
      return {
        radar: {
          radius: ["0%", "80%"],
          indicator: [
            {name: '审计取证单数'},
            {name: '被审计领导干部人数'},
            {name: '被审计单位数'},
            {name: '已落实整改数'},
            {name: '审计查询单数'},
            {name: '审计建议数'},
            {name: '审计底稿数'},
            {name: '审计处项目投入人次'},
          ],
          axisName: {
            show: true,
            color: '#363636',
            fontSize: 14,
            formatter: function (value) {
              return '['+value+']';
            }
          },
        },
        series: [
          {
            type: 'radar',
            data: this.form.radarChart.generalData,
            lineStyle: {
              type: 'dotted'
            },
            label: {
              show: true,
              color: '#252525',
              formatter: function (params) {
                return params.value;
              }
            }
          }
        ]
      }
    },
    hillChartOption() {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none'
          },
          formatter: function (params) {
            return params[0].name + ': ' + params[0].value;
          }
        },
        xAxis: {
          data: ['财务管理问题', '合规性问题', '内部控制问题', '信息系统安全问题', '绩效与效率问题', '风险管理问题', '其他问题'],
          axisTick: { show: false },
          axisLine: { show: false },
        },
        yAxis: {
          splitLine: { show: false },
          axisTick: { show: false },
          axisLine: { show: false },
          axisLabel: { show: false }
        },
        series: [
          {
            name: 'hill',
            type: 'pictorialBar',
            barCategoryGap: '-130%',
            symbol: 'path://M0,10 L10,10 C5.5,10 5.5,5 5,0 C4.5,5 4.5,10 0,10 z',
            itemStyle: {
              opacity: 0.8
            },
            emphasis: {
              itemStyle: {
                opacity: 1
              }
            },
            data:  this.form.hillChartData,
            z: 10
          },
        ]
      }
    },
    knowledgeChartOption() {
      return {
        grid: {
          top: '14%',
          right: '18%',
          bottom: '18%',
        },
        xAxis: {
          show: false,
          inverse: true,
          type: 'value',
        },
        yAxis: {
          position: 'right',
          type: 'category',
          data: ['问题库', '资料清单', '校内规章', '方案库', '外部法规'],
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
        },
        tooltip:{
          show: true
        },
        label:{
          show: true,
          position: 'left',
        },
        series: [
          {
            data: this.form.knowledgeChartData, // 知识库建设
            type: 'bar',
            barCategoryGap: '50%',
          }
        ]
      }
    },
  },
  mounted() {
    this.initChart();
    this.startAnimations(this.form.generalStatistic);
    this.autoScroll('projectData', this.form.projectData);
    this.autoScroll('procurementData', this.form.procurementData);
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.RCSChart) {
      this.RCSChart.dispose();
    }
    if (this.AEAAChart) {
      this.AEAAChart.dispose();
    }
    if (this.radarChart) {
      this.radarChart.dispose();
    }
    if (this.hillChart){
      this.hillChart.dispose()
    }
    if (this.knowledgeChart){
      this.knowledgeChart.dispose()
    }
  },
  methods: {
    // handleYearChange(val){
    //   switch (val){
    //
    //   }
    // },


    // 获取所有已经审批通过的年度计划年度
    listPlanHeadYear(){
      listPlanHeadYear().then((res) => {
        this.$set(this,"planHeadYears", res.data.data)
        if (this.planHeadYears.length > 0) {
          this.$set(this.query, 'planHeadYear', this.planHeadYears[0]); // 设置默认值为数组的第一个元素
        }
      });
    },

    // 标签栏切换
    handleClick(tab) {
      if (tab.name === '工程审计成果总览') {
        this.radarChartOption.series[0].data = this.form.radarChart.engineeringData;
        this.radarChart.setOption(this.radarChartOption);
        this.startAnimations(this.form.engineeringStatistic);
      } else if (tab.name === '常规审计成果总览'){
        this.radarChartOption.series[0].data = this.form.radarChart.generalData;
        this.radarChart.setOption(this.radarChartOption);
        this.startAnimations(this.form.generalStatistic);
      }
    },

    // 加载事件
    onLoad() {
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 1500)
      this.listPlanHeadYear();
    },

    // 表格无缝滚动
    autoScroll(tableRef, dataArray) {
      dataArray.forEach(item => {
        dataArray.push(item);
      });
      const table = this.$refs[tableRef];
      const divData = table.$refs.bodyWrapper;
      let scrollTimer = this[`scrollTimer${tableRef}`]; // 动态生成定时器名称

      const scroll = () => {
        divData.scrollTop += 1;
        if (divData.scrollTop + divData.clientHeight >= divData.scrollHeight - 10) {
          divData.scrollTop = divData.scrollTop - divData.scrollHeight/2
        }
        scrollTimer = requestAnimationFrame(scroll);
      };

      scrollTimer = requestAnimationFrame(scroll); // 启动滚动
      this[`scrollTimer${tableRef}`] = scrollTimer; // 存储定时器引用
    },

    // 统计图表
    initChart() {
      // 基于准备好的dom，初始化echarts实例
      // RCSChart: 整改完成情况
      // AEAAChart: 本年度工程审计金额
      this.RCSChart = echarts.init(this.$refs['RCSChart'], null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
      this.AEAAChart = echarts.init(this.$refs['AEAAChart'], null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
      this.radarChart = echarts.init(this.$refs['radarChart'], null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
      this.hillChart = echarts.init(this.$refs['hillChart'], null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
      this.knowledgeChart = echarts.init(this.$refs['knowledgeChart'], null, {
        renderer: 'canvas',
        useDirtyRect: false
      });

      this.RCSChart.setOption(this.RCSChartOption);
      this.AEAAChart.setOption(this.AEAAChartOption);
      this.radarChart.setOption(this.radarChartOption);
      this.hillChart.setOption(this.hillChartOption);
      this.knowledgeChart.setOption(this.knowledgeChartOption);
    },
    handleResize() {
      if (this.RCSChart) {
        this.RCSChart.resize();
      }
      if (this.AEAAChart) {
        this.AEAAChart.resize();
      }
      if (this.radarChart) {
        this.radarChart.resize();
      }
      if (this.hillChart){
        this.hillChart.resize();
      }
      if (this.knowledgeChart){
        this.knowledgeChart.resize();
      }
    },

    // 数字滚动
    startAnimations(targetValues) {
      for (const key in targetValues) {
        if (Object.prototype.hasOwnProperty.call(targetValues, key)) {
          this.startAnimation(key, targetValues[key]);
        }
      }
    },
    startAnimation(propertyName, targetValue) {
      const startValue = this.animatedValues[propertyName] || 0;
      const stepSize = (targetValue - startValue) * (this.animationStep / this.animationDuration);
      let currentValue = startValue;

      const intervalId = setInterval(() => {
        currentValue += stepSize;

        // 防止浮点数不精确问题
        if ((stepSize > 0 && currentValue >= targetValue) || (stepSize < 0 && currentValue <= targetValue)) {
          currentValue = targetValue;
          clearInterval(intervalId);
        }

        this.$set(this.animatedValues, propertyName, currentValue);
      }, this.animationStep);
    },
  },
}
</script>
